# coding=utf-8
from __future__ import (absolute_import, division, print_function, unicode_literals)

import json
import csv
from datetime import datetime
from itertools import groupby

import matplotlib
import matplotlib.pyplot as plt
# draw the line , the square of the num
import pygal
from matplotlib import pyplot
from matplotlib.ticker import MultipleLocator

from Die import Die
from RandomWalk import RandomWalk

try:
    # python 2.x版本
    from urllib2 import urlopen
except ImportError:
    # python 3.x版本
    from urllib.request import urlopen


# 练习matplotlib,绘制线
def draw_line_for_square():
    inputx = [1, 2, 3, 4, 5]
    squares = [1, 4, 9, 16, 25]
    plt.title("square", fontsize=24)
    plt.xlabel("value", fontsize=24)
    plt.ylabel("square", fontsize=24)
    plt.plot(inputx, squares, linewidth=5);
    plt.show();


# draw dot
# 练习matplotlib,绘制点
def draw_dot_for_square():
    inputx = list(range(1, 9))
    squares = [x ** 2 for x in inputx]
    plt.title("square", fontsize=24)
    plt.xlabel("value", fontsize=24)
    plt.ylabel("square", fontsize=24)
    plt.scatter(inputx, squares, c=squares, edgecolor='none', cmap=plt.cm.Blues, s=40)
    plt.show();
    # plt.savefig('square.png',bbox_inches='tight')  #保存图表


# 练习matplotlib，绘制随机分散的点，蚂蚁路径
def draw_random_walk():
    while True:
        rand = RandomWalk();
        rand.fill_walk();
        plt.figure(dpi=200, figsize=(10, 6))
        point_numbers = list(range(rand.num_points))
        plt.scatter(rand.x_values, rand.y_values, c=point_numbers, edgecolor='none', cmap=plt.cm.Blues, s=15)
        plt.scatter(0, 0, c='green', edgecolors='none', s=20)
        plt.scatter(rand.x_values[-1], rand.y_values[-1], c='red', edgecolors='none', s=10)
        # plt.axes().get_xaxis().set_visible(False)
        # plt.axes().get_yaxis().set_visible(False)

        plt.show()
        keep_running = raw_input("Make another walk? (y/n): ")
        if keep_running == 'n':
            break


# 练习pygal库绘制直方图
def pygal_test():
    die = Die()
    die2 = Die(10)
    results = []
    for roll_num in range(1000):
        result = die.roll() + die2.roll()
        results.append(result)
    print(results)
    max_sides = die.num_sides + die2.num_sides;
    frequences = []

    for side in range(2, max_sides + 1):
        frequence = results.count(side)
        frequences.append(frequence)
    print(frequences)
    hist = pygal.Bar()
    hist.title = 'Results of rolling one D6 100 times'
    hist.x_labels = ['2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16'];
    hist.x_title = 'Result'
    hist.y_title = 'Frequency of Results'
    hist.add('D6-D10', frequences)  # y轴数据
    hist.render_to_file('die_visual.svg')


# 从CVS文件（数据字段之间用逗号隔开的文件格式）里读取数据，并使用matplotlib绘制天气
def cvs_weather():
    filename = 'sitka_weather_2014.csv'
    with open(filename) as f:
        reader = csv.reader(f)
        header_row = next(reader)
        for index, col_header in enumerate(header_row):
            print(index, col_header)
        highs = []
        dates = []
        lows = []
        for row in reader:
            try:
                high = int(row[1])  # 最高温度，由于图表的Y轴数据只识别数字，所以将其转为int
                low = int(row[3])
                cur_date = datetime.strptime(row[0], "%Y-%m-%d")
            except ValueError:
                print(cur_date, 'missing data')
            else:
                highs.append(high)
                lows.append(low)  # 最低温度
                dates.append(cur_date)

        # 根据数据绘制图形
        fig = plt.figure(dpi=128, figsize=(10, 6))

        pyplot.plot(dates, highs, c='red')
        pyplot.plot(dates, lows, c='green')
        fig.autofmt_xdate()
        plt.title('Daily high temperatures, July 2014', fontsize=24)
        plt.xlabel('', fontsize=16)
        plt.ylabel("Temperatures(F)", fontsize=16)
        plt.tick_params(axis='both', which='major', labelsize=5)
        plt.fill_between(dates, highs, lows, facecolor='blue', alpha=0.1)
        pyplot.show()


# 使用matplotlib绘制疫情数据
def cvs_sars():
    matplotlib.rcParams['font.sans-serif'] = ['SimHei']
    matplotlib.rcParams['font.family'] = 'sans-serif'
    filename = 'xianyiqing2.csv'
    name = matplotlib.matplotlib_fname()
    print(name)
    with open(filename) as f:
        reader = csv.reader(f)
        header_row = next(reader)
        # for index, col_header in enumerate(header_row):
        # print(index, col_header)
        persons_nums = []
        areas = []

        for row in reader:
            try:
                cur_area = row[0]
                person_num = int(row[1])  # 最高温度，由于图表的Y轴数据只识别数字，所以将其转为int
            except ValueError:
                print(cur_area, 'missing data')
            else:
                areas.append(cur_area)
                persons_nums.append(person_num)

        # 根据数据绘制图形
        fig = plt.figure(dpi=128, figsize=(10, 6))
        # 指定默认字体
        matplotlib.rcParams['font.sans-serif'] = ['SimHei']
        matplotlib.rcParams['font.family'] = 'sans-serif'

        # 设置标题
        plt.title(u'西安各区确诊情况', fontsize=30)
        plt.xlabel('', fontsize=24)
        plt.ylabel(u'确诊人数', fontsize=10)
        plt.tick_params(axis='y', which='major', labelsize=10)
        plt.tick_params(axis='x', which='major', labelsize=10)
        # 设置Y轴刻度
        y_major_locator = MultipleLocator(1)
        ax = plt.gca()
        ax.yaxis.set_major_locator(y_major_locator)
        plt.ylim(0, 27)  # 刻度范围

        # 绘制
        plt.scatter(areas, persons_nums, c='red', s=10)  # 只描点
        plt.plot(areas, persons_nums, c='black', alpha=0.2)  # 折线
        fig.autofmt_xdate()
        plt.savefig("a.svg")
        # plt.show()


# 从json中读取数据并用pygal库来绘制折线图
def json_chart():
    json_url = 'https://raw.githubusercontent.com/muxuezi/btc/master/btc_close_2017.json'
    # response = urlopen(json_url)

    # 读取数据
    # req = response.read()
    # btc_data = json.loads(req) 可以直接从URL里读取文件数据到内存
    # 将数据写入文件
    dates2 = []
    months = []
    weeks = []
    weekdays = []
    closes = []
    filename = 'btc_close_2017_urllib.json'
    with open(filename) as f:
        # 加载JSON格式
        btc_data = json.load(f)

    for btc_dict in btc_data:
        date = btc_dict['date']
        dates2.append(date)

        month = int(btc_dict['month'])
        months.append(month)
        week = int(btc_dict['week'])
        weeks.append(week)
        weekday = btc_dict['weekday']
        weekdays.append(weekday)
        close = int(float(btc_dict['close']))
        closes.append(close)
        print("{} is month{}week{},{},the close price is{}RMB".format(date, month, week, weekday, close))
    idx_month = dates2.index('2017-12-01')
    with open('收盘价Dashboard.html', 'w') as html_file:
        html_file.write(
            '<html><head><title>Dashboard</title><meta charset="utf-8"></head><body>\n')
        for svg in [
            'a.svg', 'a.svg', 'die_visual.svg'
        ]:
            html_file.write(
                '    <object type="image/svg+xml" data="{0}" height=500></object>\n'.format(svg))  # 1
        html_file.write('</body></html>')

    # 获取一个折线图对象，x轴顺时针旋转20度，show_minor_x_labels表示不用显示所有的x轴标签
    # line_chart = pygal.Line(x_label_rotation=20, show_minor_x_labels=False)
    # line_chart.title = '收盘价（￥）'
    # line_chart.x_labels = dates  # x轴数据
    # N = 20  # X坐标每隔20天显示一次
    # line_chart.x_labels_major = dates[::N]
    # line_chart.add('收盘价', closes)  # Y轴数据
    # line_chart.render_to_file('收盘价折线图（￥）.svg')


def draw_line(x_data, y_data, title, y_legend):
    xy_map = []
    for x, y in groupby(sorted(zip(x_data, y_data)), key=lambda _: _[0]):
        y_list = [v for _, v in y]
        xy_map.append([x, sum(y_list) / len(y_list)])
    x_unique, y_mean = [zip(xy_map)]
    line_chart = pygal.Line()
    line_chart.title = title
    line_chart.x_labels = x_unique
    line_chart.add(y_legend, y_mean)
    line_chart.render_to_file(title + '.svg')
    return line_chart


# draw randomWalk蚂蚁漫步
# draw_line_for_square();
# draw_dot_for_square()
# draw_random_walk()
# pygal_test()
# cvs_weather()
# cvs_sars()
# cvs_sars()
json_chart()
